package com.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.google.common.primitives.Longs;
import com.service.AlbumService;
import com.service.AudioService;
import com.sound.common.AudioUtils;
import com.sound.common.ParamCode;
import com.sound.common.QiNiuConfig;
import com.sound.common.Response;
import com.sound.common.UpfileHandler;
import com.sound.model.AlbumModel;
import com.sound.model.AudioModel;

import io.swagger.annotations.Api;

@RestController
@Api(tags = "音频")
@RequestMapping(path = "/audio")
public class AudioController extends BaseController<AudioModel> {

	private static final Logger logger = LoggerFactory.getLogger(AudioController.class);

	@Value("${file.local.cache}")
	private String localCachePath;

	@Autowired
	public QiNiuConfig qiNiuConfig;

	@Autowired
	public AlbumService albumService;

	@Autowired
	private AudioService audioService;

	@GetMapping(path = "/findById")
	@Override
	public Response<AudioModel> findById(Long id) {
		return super.findById(id);
	}

	/**
	 * 新增专辑或者更新专辑
	 */
	@PostMapping("/save")
	@ResponseBody
	public Response<Void> save(@ModelAttribute @Valid AudioModel t, BindingResult result) {
		if (t.getId() == null) {
			AlbumModel albumModel = albumService.findById(t.getAlbumId());
			long count = albumModel.getAudioCount();
			albumModel.setAudioCount(count + 1);
			albumService.save(albumModel);
		}
		return super.save(t, result);
	}

	@PostMapping(path = "/saveImg")
	@ResponseBody
	public Response<List<Object>> saveImg(@RequestParam("file") MultipartFile file) throws Exception {
		Response<List<Object>> resp;
		if (file.isEmpty()) {
			resp = new Response<List<Object>>(false);
			resp.setRespone(ParamCode.FAIL);
			resp.setMsg("文件不能为空！");
			return resp;
		}

		resp = new Response<List<Object>>();
		String fileName = file.getOriginalFilename();
		// 上传文件到七牛云
		File file1 = null;

		String key = null;
		try {
			file1 = File.createTempFile(file.getName(), ".tmp");
			file.transferTo(file1);
			key = qiNiuConfig.upLoadAudio(file1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// System.out.println(file.getOriginalFilename());
		String cacheFilePath = "";
		String md5 = "";
		boolean isCacheLocal = false;
		if (cacheFilePath == null) {
			// 本地缓存
			UpfileHandler.saveFileLocal((File) file);
			isCacheLocal = true;
		}

		// t.setFilepath(key);
		String key1 = key;
		// t.setFileName(fileName);
		String fileName1 = fileName;
		// t.setMd5(md5);
		String md51 = md5;
		// t.setLocal(isCacheLocal);
		Boolean isCacheLocal1 = isCacheLocal;
		System.out.println(key);
		ArrayList<Object> list = new ArrayList<Object>();
		list.add(key1);
		list.add(fileName1);
		list.add(md51);
		list.add(isCacheLocal1);
		list.add(AudioUtils.getAudioSize(file));
		System.out.println(AudioUtils.getAudioSize(file));
		// list.add(ms);
		resp.setData(list);
		return resp;
	}

	@GetMapping(path = "/findAll")
	@Override
	public Response<Iterable<AudioModel>> findAll() {

		return super.findAll();
	}

	@GetMapping(path = "/deleteById")
	@Override
	public Response<Void> deleteById(Long id) {
		AudioModel audioModel = service.findById(id);
		Long aid = audioModel.getAlbumId();
		if (audioModel != null && aid != null) {
			AlbumModel albumModel = albumService.findById(aid);
			long count = albumModel.getAudioCount();
			albumModel.setAudioCount(count - 1);
			albumService.save(albumModel);
		}

		return super.deleteById(id);
	}

	private RestTemplate restTemplate = new RestTemplate();

	@GetMapping(path = "/play")

	public Response<String> play(@RequestParam(value = "datas[]") long[] auodioIds,
			@RequestParam(value = "deviceId") String deviceId, HttpServletRequest req) {
		logger.info("play:" + JSON.toJSONString(auodioIds));
		Response<String> resp = new Response<String>();
		List<Long> ids = Longs.asList(auodioIds);
		HttpSession session = req.getSession();
		String userId = "userId";
		if (null != session) {
			userId = (String) (session.getAttribute("userId"));
		}
		try {
			Iterable<AudioModel> audioModels = this.service.findAllById(ids);
			String body = restTemplate.postForObject("http://localhost:8888/remote/play/{userId}/{deviceId}",
					audioModels, String.class, userId, deviceId);
			resp.setData(body);
		} catch (Exception e) {
			logger.error("audio play fail", e);
			resp.setRespone(ParamCode.FAIL);
		}
		return resp;

	}

	/**
	 * 更改推荐级别
	 */
	@PostMapping(path = "/updatePriority")
	@ResponseBody
	public Response<Void> updatePriority(@ModelAttribute @Valid AudioModel t, BindingResult result) {
		System.out.println(t.getPriority());
		return super.save(t, result);
	}

	/**
	 * 根据推荐等级查询
	 * 
	 * @param priority
	 * @return
	 */
	@GetMapping("/findByPriority")
	@ResponseBody
	public Response<List<AudioModel>> findByPriority(@Param("priority") Integer priority) {
		Response<List<AudioModel>> resp;
		if (priority.toString() == null) {
			resp = new Response<List<AudioModel>>(false);
			resp.setMsg("参数未传递");
			return resp;
		} else if (priority < 0 || priority > 2) {
			resp = new Response<List<AudioModel>>(false);
			resp.setMsg("参数不合法");
		}
		resp = new Response<List<AudioModel>>(true);
		resp.setData(audioService.findByPriority(priority));
		return resp;
	}

	/**
	 * 分页查找节目
	 * 
	 * @param page
	 * @return
	 */
	@GetMapping(path = "/findByPage")
	@ResponseBody
	public Response<Page<AudioModel>> findByPage(int page, int size) {
		return super.findByPage(page, size);
	}

	public void method3() throws Exception {

	}

}